#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <stdexcept>

using namespace std;
// recursive_timed_mutex继承自 std::timed_mutex，允许同一线程多次获得锁，同时支持定时功能
// 1、同一线程可多次加锁（递归语义，和 recursive_mutex 一样）
// 2、加锁时可以指定超时（try_lock_for / try_lock_until，和 timed_mutex 一样）
recursive_timed_mutex rtmtx;

int shared_resource = 0;

void recursive_increment(int count)
{
    if (count <= 0)
        return;

    if (rtmtx.try_lock_for(chrono::milliseconds(100)))
    {
        this_thread::sleep_for(chrono::milliseconds(200));
        ++shared_resource;
        recursive_increment(count - 1); // 递归
        rtmtx.unlock();
    }
    else
    {
        cout << "超时 100 ms 仍未拿到锁，放弃" << endl;
    }
}

int main()
{
    thread t1(recursive_increment, 3);
    thread t2(recursive_increment, 3);

    t1.join();
    t2.join();

    cout << "Final value of shared_resource: " << shared_resource << endl;
    return 0;
}